package com.vfa.vocaburay;


import java.io.ObjectOutputStream.PutField;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.Spinner;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.TextView;

import com.vfa.data.Category;
import com.vfa.data.Language;
import com.vfa.data.QuizName;
import com.vfa.data.QuizWordsData;
import com.vfa.data.SettingActivity;
import com.vfa.data.WordData;

import com.vfa.data.toastMaking;
import com.vfa.test.InsertQuestion;

public class QuizOption extends Activity {

    private EditText username;
    private Spinner quizlanguage;
    private EditText noOfQuestions;
    private Button startQuiz;
    private Button cancle;
    private CheckBox byHand;
    private CheckBox byImport;
    private boolean isByHandChecked = false;
    private boolean isByimportChecked = false;
    private Spinner categorySpinner;
    private Spinner spQuizName;
    private static final String SETTING = "Settings";
    
    private int NumOfQuiz;
    private String quizname;
    private String user;
    ArrayList<Language> languages;
    ArrayList<Category> categoryList = vfaMain.wordData.getCategories();
    QuizWordsData quizdata;
    private ArrayList<QuizName> arrQuiz;


    // where we display the selected date and time
    private TextView mDateStartDisplay;
    private TextView mDateEndDisplay;

    // date and time
    private int mYear;
    private int mMonth;
    private int mDay;

    private int mEndYear;
    private int mEndMonth;
    private int mEndDay;

    static final int DATE_START_DIALOG_ID = 0;
    static final int DATE_END_DIALOG_ID = 1;

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.quizoption);
        /* Start Calendar */
        mDateStartDisplay = (TextView) findViewById(R.id.dateStartDisplay);
        mDateEndDisplay = (TextView) findViewById(R.id.dateEndDisplay);

        ImageButton pickStartDate = (ImageButton) findViewById(R.id.pickStartDate);
        pickStartDate.setOnClickListener(new View.OnClickListener() {

            public void onClick(View v) {
                showDialog(DATE_START_DIALOG_ID);
            }
        });
        Button startDateClear = (Button) findViewById(R.id.startDateClear);
        startDateClear.setOnClickListener(new View.OnClickListener() {

            public void onClick(View v) {
                mDateStartDisplay.setText("");
            }
        });

        ImageButton pickEndDate = (ImageButton) findViewById(R.id.pickEndDate);
        pickEndDate.setOnClickListener(new View.OnClickListener() {

            public void onClick(View v) {
                showDialog(DATE_END_DIALOG_ID);
            }
        });
        Button endDateClear = (Button) findViewById(R.id.endDateClear);
        endDateClear.setOnClickListener(new View.OnClickListener() {

            public void onClick(View v) {
                mDateEndDisplay.setText("");
            }
        });


        final Calendar c = Calendar.getInstance();
        mYear = c.get(Calendar.YEAR);
        mMonth = c.get(Calendar.MONTH);
        mDay = c.get(Calendar.DAY_OF_MONTH);

        mEndYear = c.get(Calendar.YEAR);
        mEndMonth = c.get(Calendar.MONTH);
        mEndDay = c.get(Calendar.DAY_OF_MONTH);

        //updateDisplay();
        /* End Calendar */

        username = (EditText) findViewById(R.id.userName);
        noOfQuestions = (EditText) findViewById(R.id.noOfQuestions);
        spQuizName = (Spinner) findViewById(R.id.SpQuizNme);
        quizlanguage = (Spinner) findViewById(R.id.quizLanguage);
        categorySpinner = (Spinner) findViewById(R.id.CategorySpinner);
        
        
        quizdata = new QuizWordsData(this);
        arrQuiz = new ArrayList<QuizName>();
        arrQuiz = quizdata.getAllQuizName();
        ArrayAdapter<QuizName> quizname = new ArrayAdapter<QuizName>(this, R.layout.listiterm, arrQuiz);
        quizname.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        spQuizName.setAdapter(quizname);
        
        spQuizName.setOnItemSelectedListener(onSelectsQuizName);
        quizlanguage.setOnItemSelectedListener(onSelectspLaguage);
        
        
        byHand = (CheckBox) findViewById(R.id.byHandCB);
        byImport = (CheckBox) findViewById(R.id.byImportCB);
        startQuiz = (Button) findViewById(R.id.startQuiz);
        cancle = (Button) findViewById(R.id.cancelQuizOP);
        // listener
        startQuiz.setOnClickListener(startQuiz_listener);
        cancle.setOnClickListener(cancle_listener);
        byHand.setOnCheckedChangeListener(byHand_listener);
        byImport.setOnCheckedChangeListener(byImport_listener);
        LoadSharePreferences();
    }
    
    private android.widget.AdapterView.OnItemSelectedListener onSelectsQuizName = new android.widget.AdapterView.OnItemSelectedListener(){

		@Override
		public void onItemSelected(AdapterView<?> arg0, View view, int pos,
				long arg3) {
			//System.out.println("quiz id = "+((QuizName)spUnit.getSelectedItem()).getQuizID());
			int idtemp = ((QuizName)spQuizName.getSelectedItem()).getQuizID();
			ArrayList<Language> arrLang = new ArrayList<Language>();
			arrLang = quizdata.getLangInQuiz(idtemp);
			if(arrLang.size()>0)
			{
				quizlanguage.setEnabled(true);
				ArrayAdapter<Language> adapLang;
				adapLang= new ArrayAdapter<Language>(getApplicationContext(), android.R.layout.simple_spinner_item, arrLang);
				adapLang.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
				quizlanguage.setAdapter(adapLang);
			}
		}

		@Override
		public void onNothingSelected(AdapterView<?> arg0) {
			return;
			
		}
		
	};
	
	private android.widget.AdapterView.OnItemSelectedListener onSelectspLaguage = new android.widget.AdapterView.OnItemSelectedListener(){

		@Override
		public void onItemSelected(AdapterView<?> arg0, View view, int pos,
				long arg3) {
			int idquiztemp = ((QuizName)spQuizName.getSelectedItem()).getQuizID();
			int idlangtemp = ((Language)quizlanguage.getSelectedItem()).getLanguageID();
			ArrayList<Category> arrCata = new ArrayList<Category>();
			
			Category catetemp = new Category();
			catetemp.setCategoryID(0);
			catetemp.setCategoryName("All");
			arrCata.add(0, catetemp);
			
			arrCata.addAll(quizdata.getCataInLang(idquiztemp , idlangtemp));
			if(arrCata.size()>0)
			{
				categorySpinner.setEnabled(true);
				ArrayAdapter<Category> adapCata;
				adapCata=new ArrayAdapter<Category>(getApplicationContext(), android.R.layout.simple_spinner_item, arrCata);
				adapCata.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
				categorySpinner.setAdapter(adapCata);
			}
			
		}

		@Override
		public void onNothingSelected(AdapterView<?> arg0) {
			return;
			
		}
		
	};

    private OnCheckedChangeListener byHand_listener = new OnCheckedChangeListener() {

        @Override
        public void onCheckedChanged(CompoundButton buttonView,
                boolean isChecked) {
            isByHandChecked = isChecked;

        }
    };
    private OnCheckedChangeListener byImport_listener = new OnCheckedChangeListener() {

        @Override
        public void onCheckedChanged(CompoundButton buttonView,
                boolean isChecked) {
            isByimportChecked = isChecked;
        }
    };
    private OnClickListener startQuiz_listener = new OnClickListener() {

        @Override
        public void onClick(View v) {
            Date startDate = new Date(mYear-1900,mMonth,mDay);
            Date endDate = new Date(mEndYear-1900,mEndMonth,mEndDay);
            DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
            String strStartDate = mDateStartDisplay.getText().equals("") ? "" : df.format(startDate);
            String strEndDate = mDateEndDisplay.getText().equals("") ? "" : df.format(endDate);
            int question = 0;
            int maxOptionQuestion = 4;
            String myLanguage = quizlanguage.getSelectedItem().toString();
            String categoryId = vfaMain.wordData.getCategoryIdByName(categorySpinner.getSelectedItem().toString());
            int itemsByFile = vfaMain.wordData.getRowNumberByFile(myLanguage,categoryId, strStartDate, strEndDate);
            int itemsByHand = vfaMain.wordData.getRowNumberByHand(myLanguage,categoryId, strStartDate, strEndDate);
            int itemsByLanguage = vfaMain.wordData.getRowNumber(myLanguage,categoryId, strStartDate, strEndDate);


            // dien thong tin
            if (username.getText().toString().equals("")
                    || noOfQuestions.getText().toString().equals("")) {
                toastMaking.errorToast(getApplicationContext(),
                        "Fill all spaces !").show();
            } else { // day du thong tin
                question = Integer
                        .parseInt((noOfQuestions.getText().toString()));
                // so cau hoi nhieu hon 50
                if (question > 50 || question == 0) {
                    toastMaking.errorToast(getApplicationContext(),
                            "Max is 50. Min is 1").show();
                } else if (getInputMethod() == 0 && (question > itemsByLanguage || itemsByLanguage < maxOptionQuestion)) {
                    toastMaking.errorToast(getApplicationContext(),
                            "Available is " + itemsByLanguage + ". Change your options")
                            .show();
                } else if (getInputMethod() == 1 && (question > itemsByHand || itemsByHand < maxOptionQuestion)) {
                    toastMaking.errorToast(getApplicationContext(),
                            "Word import by hand not enough. Change your options")
                            .show();
                } else if (getInputMethod() == 2 && (question > itemsByFile || itemsByFile < maxOptionQuestion)) {
                    toastMaking.errorToast(getApplicationContext(),
                            "Available is " + itemsByFile + ". Change your options")
                            .show();
                } else {
                    Intent intent = new Intent(QuizOption.this, Quiz.class);
                    intent.putExtra("userName", username.getText().toString())
                            .putExtra("language",
                                    quizlanguage.getSelectedItem().toString())
                            .putExtra("inputMethod", getInputMethod())
                            .putExtra("categoryId", categoryId)
                            .putExtra("question", question)
                    		.putExtra("quizname", spQuizName.getSelectedItem().toString());
                    startActivity(intent);
                    QuizOption.this.finish();
                }
            }
        }
    };
    private OnClickListener cancle_listener = new OnClickListener() {

        @Override
        public void onClick(View v) {
        	AlertDialog.Builder bd = new AlertDialog.Builder(QuizOption.this);
			bd.setMessage("Are you want to exit?").setCancelable(false)
			.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
				
				@Override
				public void onClick(DialogInterface dialog, int which) {
		            QuizOption.this.finish();		
				}
			});
			bd.setNegativeButton("No", new DialogInterface.OnClickListener() {
				
				@Override
				public void onClick(DialogInterface dialog, int which) {
					dialog.cancel();
					
				}
			}).show();
        }
    };
    
    protected void onRestart() {
    	super.onRestart();
    	LoadSharePreferences();
    };
    
    private int getInputMethod() {
        int inputMethod = 0;
        if (isByHandChecked == true && isByimportChecked == false) {
            inputMethod = 1;
            // inputMethod = "hand";
        } else if (isByimportChecked == true && isByHandChecked == false) {
            inputMethod = 2;
            // inputMethod = "import";
        }
        return inputMethod;
    }
    

    @Override
    public void onBackPressed() {
       
        QuizOption.this.finish();
    }
    
    @Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// TODO Auto-generated method stub
		super.onCreateOptionsMenu(menu);
		CreateMenu(menu);
		return true;
	}
    
    @Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// TODO Auto-generated method stub
		super.onOptionsItemSelected(item);
		return MenuChoice(item);
	}

    
    private void CreateMenu(Menu menu){
    	menu.add(0,0,0,SETTING);
    }
    
    private boolean MenuChoice(MenuItem item)
    {
 	switch (item.getItemId()) {
 	case 0:
 		Intent intentshare = new Intent(QuizOption.this, SettingQuizOption.class);
 		startActivity(intentshare);
 		return true;
 	}
 	return false;
    }

    private ArrayList<String> getAllCategory(){
        ArrayList<String> categoryNames = new ArrayList<String>();
        categoryNames.add("All");
        for (Category category : categoryList) {
            categoryNames.add(category.getCategoryName());
        }
        return categoryNames;
    }

    @Override
    protected Dialog onCreateDialog(int id) {
        switch (id) {
            case DATE_START_DIALOG_ID:
                return new DatePickerDialog(this,
                        mStartDateSetListener,
                        mYear, mMonth, mDay);
            case DATE_END_DIALOG_ID:
                return new DatePickerDialog(this,
                            mEndDateSetListener,
                            mEndYear, mEndMonth, mEndDay);
        }
        return null;
    }

    @Override
    protected void onPrepareDialog(int id, Dialog dialog) {
        switch (id) {
            case DATE_START_DIALOG_ID:
                ((DatePickerDialog) dialog).updateDate(mYear, mMonth, mDay);
                break;
            case DATE_END_DIALOG_ID:
                ((DatePickerDialog) dialog).updateDate(mEndYear, mEndMonth, mEndDay);
                break;
        }
    }

    private void updateStartDateDisplay() {
        mDateStartDisplay.setText(
            new StringBuilder()
                // Month is 0 based so add 1
                .append(mYear).append("-")
                .append(mMonth + 1).append("-")
                .append(mDay).append(" "));
    }

    private void updateEndDateDisplay() {
        mDateEndDisplay.setText(
            new StringBuilder()
                // Month is 0 based so add 1
                .append(mEndYear).append("-")
                .append(mEndMonth + 1).append("-")
                .append(mEndDay).append(" "));
    }

    private DatePickerDialog.OnDateSetListener mStartDateSetListener =
            new DatePickerDialog.OnDateSetListener() {

                public void onDateSet(DatePicker view, int year, int monthOfYear,
                        int dayOfMonth) {
                    mYear = year;
                    mMonth = monthOfYear;
                    mDay = dayOfMonth;
                    updateStartDateDisplay();
                }
            };

    private DatePickerDialog.OnDateSetListener mEndDateSetListener =
            new DatePickerDialog.OnDateSetListener() {

                public void onDateSet(DatePicker view, int year, int monthOfYear,
                        int dayOfMonth) {
                    mEndYear = year;
                    mEndMonth = monthOfYear;
                    mEndDay = dayOfMonth;
                    updateEndDateDisplay();
                }
            };
   

    private static String pad(int c) {
        if (c >= 10)
            return String.valueOf(c);
        else
            return "0" + String.valueOf(c);
    }
    
    private void LoadSharePreferences(){
    	SharedPreferences sharePref = getSharedPreferences(SettingQuizOption.prefName, MODE_PRIVATE);
    	NumOfQuiz = sharePref.getInt(SettingQuizOption.NUMBERQS, 10);
    	noOfQuestions.setText(String.valueOf(NumOfQuiz));
    	user = sharePref.getString(SettingQuizOption.USER, "Admin");
    	username.setText(user);
    	quizname = sharePref.getString(SettingQuizOption.QUIZNAME, spQuizName.getSelectedItem().toString());
    	setPositionSpinerQuizname();
    }
    

	private void setPositionSpinerQuizname(){
		for(int i = 0;  i < arrQuiz.size(); i++){
			if(spQuizName.getItemAtPosition(i).toString().equals(quizname)){
				spQuizName.setSelection(i);
			}
		}
	}
	
	
}
